export default {
  props: {},
  data () {
    return {
      userInfo: {},
      dictionaries: { // 字典数据
        sale_status: [] // 状态
      },
      channelList: [], // 入栈方式、渠道
      orgCodeList: [], // 公司部门 列表
      staffList: [], // 员工 列表
      parArray: [], // 按钮权限
      // visible 是否显示 | title 弹窗标题 | type 类型 | width 默认宽 | row 参数 | batch 是否批量
      dialog: { visible: false, title: '编辑', width: '640px', type: '', row: {}, batch: false },
      trend: { // 销售总额7天变化趋势
        loading: false,
        title: '销售总额7天变化趋势',
        type: 'trend',
        orgCode: '', // 公司部门
        dateArr: [], // 日期
        config: {
          maxNum: 100,
          dateList: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
        },
        baseData: { total: '23456.00', subTotal: '13456.00', average: '13456.00', increase: '75.00' },
        dataList: [
          {
            color: '#4168e7',
            name: 'GMV',
            list: [56.5, 82.1, 88.7, 70.1, 53.4, 85.1, 56.5, 82.1, 88.7, 70.1, 53.4, 85.1]
          },
          {
            color: '#14d8cb',
            name: '环比金额',
            list: [16.5, 42.1, 78.7, 64.1, 23.4, 89.1, 46.5, 32.1, 68.7, 80.1, 55.4, 75.1]
          }
        ]
      }
    }
  },
  computed: {},
  created () {
    this.userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
    // 获取字典值
    for (const type in this.dictionaries) {
      this.getDictionaries(type)
    }
    // this.getButtonTreeDto()
    this.initializationData() // 初始化数据
  },
  methods: {
    // 获取字典数据
    getDictionaries (type) {
      if (type && this.dictionaries[type].length > 0) {
        return
      }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
      }).catch((err) => {
        console.log(err)
      })
    },
    // 初始化数据
    initializationData () {
      const matched = this.$route.matched
      this.getChannelList() // 获取 入栈方式、渠道
      this.getOrgTreeList() // 公司部门
      const routeName = this.$route.name
      // console.log(routeName)
      switch (routeName) {
        case 'dataBoardIndex':
          // 首页
          this.getVariation(true) // 销售总额XX天变化趋势
          break
        case 'dataBoardOrder':
          // 订单
          this.getVariation(true) // 销售总额XX天变化趋势
          break
        default: // 首页
          // console.log(matched[matched.length - 1].meta.title)
      }
    },
    // 获取 入栈方式、渠道
    getChannelList () {
      const params = { pageNo: 1, pageSize: 999 }
      this.$api.selectCustomerditch(params).then((res) => {
        if (res.code == 0) {
          this.channelList = res.data // 入栈方式、渠道
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 公司部门
    getOrgTreeList (params) {
      // orgProcessOrgList
      const paramsVersion = { 'request': { 'orgName': '', 'orgType': '' }, 'version': '' }
      const orgCodeList = JSON.parse(sessionStorage.getItem('orgCodeList'))
      if (orgCodeList && orgCodeList.length > 0) {
        // console.log(orgCodeList)
        this.orgCodeList = orgCodeList
        // return console.log('dataBoardCommon 公司部门 已经有数据，不需要请求！')
        return
      }
      this.$api.orgTreeList(paramsVersion).then((res) => {
        if (res.code === 0) {
          this.orgCodeList = res.data
          // 存本地缓存
          sessionStorage.setItem('orgCodeList', JSON.stringify(res.data))
        }
        /*
        // id 为 1 的超级管理员不做默认
        const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
        if (userInfo && userInfo.id !== 1) {
          if (res.data[0].children) {
            // const orgCode = JSON.parse(sessionStorage.getItem('orgCode'))
            this.searchForm.orgCode = [...userInfo.orgCodes]
          } else {
            this.searchForm.orgCode.push(userInfo.orgCode)
          }
        }
        */
      }).catch((err) => {
        console.log(err)
      })
    },
    // 部门查询员工
    getSelectAllWithLeft (orgCodeArr) {
      const orgCodeStr = orgCodeArr.join(',')
      this.staffList = []
      if (orgCodeStr == 'undefined' || !orgCodeStr || !/[^\s]/.test(orgCodeStr)) { return }
      const params = { pageNo: 1, pageSize: 999, orgCode: orgCodeStr }
      // return console.log(params)
      this.$api.selectLastMonth(params).then((res) => {
        if (res.code == 0) {
          this.staffList = res.data
          // 存本地缓存
          // sessionStorage.setItem('staffList', JSON.stringify(res.data))
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 表格 查看 按钮
    showDetail (row) {
      const dialog = {
        visible: true,
        title: '员工业绩统计',
        type: 'performanceStatistics',
        width: '1300px',
        row,
        batch: false,
        subTitle: '(时间：2022年6月)'
      }
      this.dialog = dialog
      console.log('showDetail 查看', this.dialog)
      this.staffTableAchievementDetail.month = row.submitDate
      this.getSelectEmployeeKpi(row)
    },
    // 员工业绩统计(XX年XX月)
    getSelectEmployeeKpi (row) {
      this.loading = true
      this.staffTableAchievementDetail.page.list = []
      const params = {
        orderTime: this.staffTableAchievementDetail.month,
        pageNo: this.staffTableAchievementDetail.page.pageNo,
        pageSize: this.staffTableAchievementDetail.page.pageSize
      }
      this.$api.selectEmployeeKpi(params).then((res) => {
        const resDataList = res.data.list
        resDataList.forEach(item => {
          // 支付下单数
          item.payPlaceOrderNumNum = Number(item.payPlaceOrderNum)
          item.payPlaceOrderNum = this.formatNumber(item.payPlaceOrderNum, 0)
          // 待审核订单数
          item.approveOrderNumNum = Number(item.approveOrderNum)
          item.approveOrderNum = this.formatNumber(item.approveOrderNum, 0)
          // 老客下单数
          item.oldPlaceOrderNumNum = Number(item.oldPlaceOrderNum)
          item.oldPlaceOrderNum = this.formatNumber(item.oldPlaceOrderNum, 0)
          // 新客下单数
          item.newPlaceOrderNumNum = Number(item.newPlaceOrderNum)
          item.newPlaceOrderNum = this.formatNumber(item.newPlaceOrderNum, 0)
          // 新客下单率
          item.newPlaceOrderNumRateNum = Number(item.newPlaceOrderNumRate)
          item.newPlaceOrderNumRate = this.formatNumber(item.newPlaceOrderNumRate, 2)
          // 复购
          item.oldPlaceOrderNumRateNum = Number(item.oldPlaceOrderNumRate)
          item.oldPlaceOrderNumRate = this.formatNumber(item.oldPlaceOrderNumRate, 2)
          // 下单金额
          item.placeOrderTotalMoneyNum = Number(item.placeOrderTotalMoney)
          item.placeOrderTotalMoney = this.formatNumber(item.placeOrderTotalMoney, 2)
          // 老客下单金额
          item.oldPlaceOrderTotalMoneyNum = Number(item.oldPlaceOrderTotalMoney)
          item.oldPlaceOrderTotalMoney = this.formatNumber(item.oldPlaceOrderTotalMoney, 2)
          // 新客下单金额
          item.newPlaceOrderTotalMoneyNum = Number(item.newPlaceOrderTotalMoney)
          item.newPlaceOrderTotalMoney = this.formatNumber(item.newPlaceOrderTotalMoney, 2)
          // 老客下单金额占比
          item.oldPlaceOrderTotalMoneyRateNum = Number(item.oldPlaceOrderTotalMoneyRate)
          item.oldPlaceOrderTotalMoneyRate = this.formatNumber(item.oldPlaceOrderTotalMoneyRate, 2)
          // 新客下单金额占比
          item.newPlaceOrderTotalMoneyRateNum = Number(item.newPlaceOrderTotalMoneyRate)
          item.newPlaceOrderTotalMoneyRate = this.formatNumber(item.newPlaceOrderTotalMoneyRate, 2)
        })
        this.staffTableAchievementDetail.page.list = resDataList
        this.staffTableAchievementDetail.page.totalNum = res.data.totalNum
        this.loading = false
        console.log('员工业绩统计(XX年XX月)', this.staffTableAchievementDetail.page.list)
      }).catch((err) => {
        this.loading = false
        console.log(err)
      })
    },
    baseDataInit () { // 基础数据初始化 格式
      const baseDataList = this.baseDataList
      const formatNumberFun = this.formatNumber
      baseDataList.forEach((item, index) => {
        this.baseDataList[index].totalNumber = formatNumberFun(item.totalNumber, 2)
      })
    },
    // 销售总额XX天变化趋势 -- 使用页面：首页、订单
    getVariation (isDefault, dateArr, orgCodeArrStr) {
      this.trend.loading = true
      // const defaultOrgCode = this.userInfo.orgCode
      this.trend.orgCode = orgCodeArrStr ? orgCodeArrStr : this.userInfo.orgCode
      let days = 6
      // console.log(this.trend.dateArr.length > 0, this.trend.dateArr)
      if (isDefault) { // 默认
        this.trend.dateArr = this.defaultDateTime(days)
      } else { // 选择
        this.trend.dateArr = this.chooseDateTime(dateArr)
        if (this.trend.dateArr[0].indexOf('undefined') > -1) {
          this.trend.dateArr = this.defaultDateTime(days)
        }
        days = this.trend.dateArr[2]
      }
      this.trend.title = `销售总额${days + 1}天变化趋势`
      // console.log(this.trend)
      const params = {
        pageNo: 1, pageSize: 999,
        startTime: this.trend.dateArr[0],
        endTime: this.trend.dateArr[1],
        orgCode: this.trend.orgCode
        // orgCode: 'DT374265477'
      }
      this.$api.variation(params).then((res) => {
        this.trend.loading = false
        if (res.code == 0) {
          const resData = res.data
          const total = this.formatNumber(resData.totalMoney, 2)
          // const subTotal = this.formatNumber(resData.avgTotalMoney,2)
          const average = this.formatNumber(resData.avgTotalMoney, 2)
          this.trend.baseData = {
            total,
            subTotal: total,
            average,
            // increaseNum: Number(resData.totalMoneyGrowthRate),
            increaseNum: isNaN(Number(resData.totalMoneyGrowthRate)) ? 0.00 : Number(resData.totalMoneyGrowthRate),
            increase: this.formatNumber(resData.totalMoneyGrowthRate, 0)
          }
          const maxNumArr = [...resData.totalMoneyList, ...resData.sequentialTotalMoneyList]
          this.trend.config.maxNum = Math.max(...maxNumArr) + 10
          this.trend.config.dateList = resData.timeNoes
          this.trend.dataList[0].list = resData.totalMoneyList
          this.trend.dataList[1].list = resData.sequentialTotalMoneyList
        }
      }).catch((err) => {
        this.trend.loading = false
        console.log(err)
      })
    },
    receiveSearchData (obj) {
      console.log('接收SearchData-Common', obj.type, obj)
      const type = obj.type
      const dateArr = obj.searchFormData.companyDate
      const orgCodeArr = obj.searchFormData.orgCode
      let orgCodeArrStr = ''
      if (orgCodeArr) {
        orgCodeArr.forEach(item => {
          orgCodeArrStr += `${item[item.length - 1]},`
        })
        if (typeof orgCodeArrStr === 'string' && orgCodeArrStr.length > 0) {
          orgCodeArrStr = orgCodeArrStr.substr(0, orgCodeArrStr.length - 1)
        }
      }
      // console.log(orgCodeArrStr)
      switch (type) {
        case 'staffTable':
          this.getEmployeeRanking(false, dateArr, orgCodeArrStr) // 员工排行榜
          break
        case 'trend':
          this.getVariation(false, dateArr, orgCodeArrStr) // 首页、订单 销售总额XX天变化趋势
          break
        case 'orderAmount':
          this.getPlaceOrderMoneyDist(false, dateArr, orgCodeArrStr) // 订单页面 - 下单金额分布占比
          break
        case 'orderAmountPlatform':
          this.getPlatformStatisticsCustomer(false, dateArr, orgCodeArrStr) // 客户 - 各平台客户来源占比
          break
        case 'frequency':
          this.getCountStatisticsCustomer(false, dateArr, orgCodeArrStr) // 客户 - 客户购买频次分布
          break
        case 'contrastPeople':
          this.getContrastPeople(false, dateArr, orgCodeArrStr) // 客户 - 新老客户人数比
          break
        case 'contrastMoney':
          this.getAmountStatisticsCustomer(false, dateArr, orgCodeArrStr) // 客户 - 新老客户购买金额对比
          break
        case 'categorySales':
          this.getDataGoodsCategory(false, dateArr, orgCodeArrStr) // 商品 - 各类目的销售情况
          break
        case 'productOrderCancellation':
          this.getDataGoodsRefund(false, dateArr, orgCodeArrStr) // 商品 - 各商品订单取消、退货退款概况
          break
        case 'topOrder':
          this.getDataGoodsCountOrder(false, dateArr, orgCodeArrStr) // 商品 - 商品销量订单 Top10
          break
        case 'amount':
          console.log(type)
          this.getDataGoodsCount(false, dateArr, orgCodeArrStr) // 商品 - 商品销售量 Top10
          break
        case 'user': // 用户运营看板
          // console.log(obj.changeDate[0], obj.changeDate[0].indexOf('undefined') === -1)
          if (obj.changeDate[0].indexOf('undefined') === -1) {
            this.basicDays = 10000
            this.baseData.dateArr = obj.changeDate
            this.getStatistics()
          } else {
            // debugger
            this.basicDays = obj.outputDate
            if (obj.outputDate === 1 || obj.outputDate === 1001 || obj.outputDate === 1071 || obj.outputDate === 1031) {
              this.getStatistics(false)
            }
          }
          break
        case 'platformProportion':
          console.log(type)
          this.getPlatformStatisticsCustomer(false, dateArr, orgCodeArrStr) // 用户 - 客户 平台
          break;
        case 'userlayerProportion':
          console.log(type)
          this.getMatrixUserVipData(false, dateArr, orgCodeArrStr) // 用户 - 各等级占比
          break;
        case 'bronze' || 'silver' || 'gold':
          console.log(type)
          this.getMatrixPreferenceData(type, false, dateArr, orgCodeArrStr) // 用户 - 各等级占比
          break;
        case 'recommend':
          console.log(type)
          this.getMatrixPreferenceData(type, false, dateArr, orgCodeArrStr) // 用户 - 各等级占比
          break;
        case 'renewRankingList':
          console.log(type)
          this.getMatrixPreferenceData(type, false, dateArr, orgCodeArrStr) // 用户 - 各等级占比
          break;
        default:
          const route = this.$route
          // console.log(this.$route)
          if (obj.searchFormData.staffCode) {
            this.baseData.userId = obj.searchFormData.staffCode
          }
          // 入栈方式、渠道
          // if (obj.searchFormData.channel) { this.baseData.userDitch = obj.searchFormData.channel }
          if (route.name === 'dataBoardCustomer') {
            this.baseData.userDitch = obj.searchFormData.channel
          }
          // this.baseData.userDitch = obj.searchFormData.channel
          this.baseData.orgCode = orgCodeArrStr
          this.baseData.userId = obj.searchFormData.staffCode

          if (dateArr) {
            this.baseData.dateArr = dateArr
          }
          // days 1 今天
          // days 1001 昨天
          // days 1070 过去七天
          // days 1071 本周
          // days 1031 本月
          // days 10000 自定义时段
          this.basicDays = obj.outputDate
          if (obj.outputDate === 10000) {
            this.baseData.dateArr = obj.changeDate
          }
          // debugger
          if (obj.outputDate === 1 || obj.outputDate === 1001 || obj.outputDate === 1071 || obj.outputDate === 1031) {
            this.getStatistics(false)
          }
        // console.log('顶部搜索', this.baseData)
      }
    },
    // 选择日期时间
    chooseDateTime (dateArr) {
      // 参数 dateArr 组件 日期范围
      // const startTime = new Date()
      const nowTime = new Date()

      const YY = nowTime.getFullYear()// 年
      const MM = nowTime.getMonth() + 1 // 月
      const DD = nowTime.getDate() // 日
      const hh = nowTime.getHours() // 小时
      const mm = nowTime.getMinutes() // 分钟
      const ss = nowTime.getSeconds() // 秒
      // this.searchForm.diyTime[1] = `${this.searchForm.diyTime[1]} ${hh}:${mm}:${ss}`
      // const nowDateTime = `${dateArr[1]} ${hh}:${mm}:${ss}`
      let nowDateTime = `${dateArr[1]}`
      if (dateArr[1].indexOf('23:59:59') === -1) {
        nowDateTime = `${dateArr[1]} 23:59:59`
      }
      const nowTimeReset = `${hh}:${mm}:${ss}`

      // const pastDateTime = `${sYY}-${sMM}-${sDD} ${shh}:${smm}:${sSS}`
      let pastDateTime = `${dateArr[0]}`
      if (dateArr[0].indexOf('00:00:00') === -1) {
        pastDateTime = `${dateArr[0]} 00:00:00`
      }
      // 两日期相差的天数
      const between = this.getDaysBetween(dateArr[0], dateArr[1])
      // console.log([pastDateTime, nowDateTime, between])
      return [pastDateTime, nowDateTime, between]
    },
    // 默认日期时间
    defaultDateTime (days, dateArr) {
      // 参数 days 天数
      const startTime = new Date()
      const nowTime = new Date()
      // console.log('defaultDateTime', nowTime)
      // debugger
      // console.log(new Date().toLocaleString())
      const YY = nowTime.getFullYear()// 年
      let MM = nowTime.getMonth() + 1 // 月
      let DD = nowTime.getDate() // 日
      const hh = nowTime.getHours() // 小时
      const mm = nowTime.getMinutes() // 分钟
      const ss = nowTime.getSeconds() // 秒
      if (MM.toString().length === 1) {
        MM = '0' + MM.toString()
      }
      if (DD.toString().length === 1) {
        DD = '0' + DD.toString()
      }
      // this.searchForm.diyTime[1] = `${this.searchForm.diyTime[1]} ${hh}:${mm}:${ss}`
      // const nowDateTime = `${YY}-${MM}-${DD} ${hh}:${mm}:${ss}`
      const nowDateTime = `${YY}-${MM}-${DD} 23:59:59`
      // console.log(nowDateTime)
      // console.log(nowTime.getTime() - 3600 * 1000 * 24 * 7)

      // 过去日期时间 获取现在的时间戳 减 相差的时间戳
      const pastTense = new Date(startTime.getTime() - 3600 * 1000 * 24 * days)
      // const pastTense = startTime.setTime(startTime.getTime() - 3600 * 1000 * 24 * days)

      // 过去日期时间
      const sYY = pastTense.getFullYear()// 年
      let sMM = pastTense.getMonth() + 1 // 月
      let sDD = pastTense.getDate() // 日
      const shh = pastTense.getHours() // 小时
      const smm = pastTense.getMinutes() // 分钟
      const sSS = pastTense.getSeconds() // 秒
      if (sMM.toString().length === 1) {
        sMM = '0' + sMM.toString()
      }
      if (sDD.toString().length === 1) {
        sDD = '0' + sDD.toString()
      }
      // const pastDateTime = `${sYY}-${sMM}-${sDD} ${shh}:${smm}:${sSS}`
      let pastDateTime = `${sYY}-${sMM}-${sDD} 00:00:00`
      // console.log(pastDateTime)
      if (days == 1) {
        pastDateTime = `${YY}-${MM}-${DD} 00:00:00`
      }
      // 两日期相差的天数
      const between = this.getDaysBetween(`${sYY}-${sMM}-${sDD}`, `${YY}-${MM}-${DD}`)
      // console.log([pastDateTime, nowDateTime, between])
      if (days === 1001) { // 昨天
        const { startDate, enDate } = this.getPastDays(1)
        console.log(startDate, enDate)
        return [startDate, enDate, 1]
      } else if (days === 1070) { // 过去七天
        const { startDate, enDate } = this.getPastDays(7)
        // console.log(startDate, enDate)
        return [startDate, enDate, 1]
      } else {
        return [pastDateTime, nowDateTime, between]
      }
    },
    /**
     * @param startDate  开始日期 yyyy-MM-dd
     * @param enDate  结束日期 yyyy-MM-dd
     * @returns {number} 两日期相差的天数
     */
    getDaysBetween (startDate, enDate) {
      // substring 字符串截取为了防止 日期 带有时间
      const sDate = Date.parse(startDate.substring(0, 10))
      const eDate = Date.parse(enDate.substring(0, 10))
      if (sDate > eDate) {
        return 0
      }
      if (sDate === eDate) {
        // return 1
        return 0
      }
      const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000)
      // debugger
      return days
    },
    // 获取过去日期
    getPastDays (days) {
      const today = new Date()
      const pastDay = new Date(today)
      const startDay = new Date(today) // 大于一天使用
      pastDay.setDate(pastDay.getDate() - 1)
      const pastDayTime = new Date(pastDay.toDateString())
      // 过去日期时间
      const sYY = pastDayTime.getFullYear() // 年
      let sMM = pastDayTime.getMonth() + 1 // 月
      let sDD = pastDayTime.getDate() // 日
      if (sMM.toString().length === 1) {
        sMM = '0' + sMM.toString()
      }
      if (sDD.toString().length === 1) {
        sDD = '0' + sDD.toString()
      }
      const startDate = `${sYY}-${sMM}-${sDD} 00:00:00`
      const enDate = `${sYY}-${sMM}-${sDD} 23:59:59`
      let obj = { startDate, enDate }
      if (days > 1 || days < 10000) {
        // debugger
        startDay.setDate(pastDay.getDate() - days)
        const startDayTime = new Date(startDay.toDateString())
        // 过去日期时间
        const startYY = startDayTime.getFullYear() // 年
        let startMM = startDayTime.getMonth() + 1 // 月
        let startDD = startDayTime.getDate() // 日
        if (startMM.toString().length === 1) {
          startMM = '0' + startMM.toString()
        }
        if (startDD.toString().length === 1) {
          startDD = '0' + startDD.toString()
        }
        const startDate = `${startYY}-${startMM}-${startDD} 00:00:00`
        const enDate = `${sYY}-${sMM}-${sDD} 23:59:59`
        obj = { startDate, enDate }
        if (days < 1001) { // 昨天
          const startDate = `${sYY}-${sMM}-${sDD} 00:00:00`
          const enDate = `${sYY}-${sMM}-${sDD} 23:59:59`
          obj = { startDate, enDate }
        }
      }
      // console.log(obj)
      return obj
    },

    // 数字格式
    formatNumber (price, num) {
      // let comma = price
      let comma
      // const priceNumber = Number(price) === NaN ? Number(price) : 0
      const priceNumber = isNaN(Number(price)) ? 0 : Number(price)
      if (num) {
        comma = priceNumber.toFixed(num)
      } else {
        // comma = Number(price).toFixed(2)
        comma = priceNumber
      }
      comma = String(comma).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
      return comma
    },
    // 防抖
    simpleDebounce (fn, delay = 100) {
      let timer = null
      return function () {
        let args = arguments
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          fn.apply(this, args)
        }, delay)
      }
    }
  }
}
